package com.example.demo.controller;

import com.example.demo.model.Message;
import com.example.demo.service.MessageService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Select;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/message")
public class MessageController {
    @Resource(name = "messageService")
    private MessageService messageService;

    @RequestMapping("/getList")
    public List<Message> getMessage(){
        try {
            log.info("获取列表信息");
            return messageService.getMessage();
        }catch (Exception e){
            log.error("获取列表失败，请联系管理员工 e{}",e);
            return null;
        }

    }

    @RequestMapping(value = "/publish",produces = "application/json")
    public String publish(@RequestBody Message message) {
        log.info("提交message {}",message);
        //参数校验
        if (!StringUtils.hasLength(message.getMessage())||!StringUtils.hasLength(message.getFrom())||!StringUtils.hasLength(message.getTo())) {
            return "{\n" +
                    "    \"ok\": 0\n" +
                    "}";
        }
        Integer result=messageService.addMessage(message);
        if(result==1){
            return "{\n" +
                    "    \"ok\": 1\n" +
                    "}";
        }else{
            return "{\n" +
                    "    \"ok\": 0\n" +
                    "}";
        }

    }
}
